const funcs = require('./funcs');
const express = require('express');
const app = express();
const port = process.env.PORT || 8086;

const ROOT = './build';
let GAMES = {};
let HIGHSCORES = [];
let SEED = "";

app.use(express.static(ROOT));
app.use(express.urlencoded({extended: true}));
app.use(express.json());

app.post('/game', function(req, res) {

  const gameInfo = req.body;

  //console.log(gameInfo);
  if(gameInfo.name && gameInfo.seed && gameInfo.tiles && gameInfo.player && gameInfo.bunnies)
  {
    const key = `${gameInfo.prefix}-${gameInfo.name.trim()}`;
    GAMES[key] = {
      key: key,
      name: gameInfo.name,
      data: {
        tiles: gameInfo.tiles,
        player: gameInfo.player,
        bunnies: gameInfo.bunnies
      },
      seed: gameInfo.seed,
      timestamp: new Date()
    };

    funcs.sendOk(res);
  }
});

app.post('/score', function(req, res) {
  const scoreInfo = req.body;
  
  if(scoreInfo.name && scoreInfo.score && scoreInfo.seed)
  {
    HIGHSCORES.push({
      name: scoreInfo.name.trim(),
      score: scoreInfo.score,
      seed: scoreInfo.seed,
      timestamp: new Date()
    });
    HIGHSCORES = HIGHSCORES.sort(funcs.compareHighscores).slice(0, 20);

    funcs.sendOk(res);
  }
});

app.post('/seed', function(req, res) {
  console.log(req.body);
  SEED = req.body.seed;
  funcs.sendOk(res);
});

app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/high-scores', (req, res) => {
  res.send(Object.values(HIGHSCORES));
});

app.get('/seed', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({ seed: SEED }));
});

app.get('/games', (req, res) => {
  if(req.query.key)
    res.send(GAMES[req.query.key] || {});
  else
    res.send(Object.values(GAMES));
});

app.get('/*', (req, res) => {
  res.sendFile('index.html', {root: './build/'});
});

setInterval(() => {
  const gameCount = Object.keys(GAMES).length;

  funcs.filterOldRecords(GAMES);

  const gameCount2 = Object.keys(GAMES).length;

  if(gameCount2 !== gameCount) console.log(`Deleted ${gameCount - gameCount2} games`);
}, 5000);